<template>
  <!-- 台风伸缩窗口 -->
  <div class="typhoonInfo-box" style="width: 450px">
    <div class="typhoonInfo-box-control">
      <span>台<br />风<br />信<br />息</span>
    </div>
    <div
      class="typhoonInfo-title"
      style="display: flex; align-items: center; justify-content: center"
    >
      <span>台风历史列表</span>
      <img
        :src="iconClose"
        alt=""
        style="height: 20px; position: absolute; right: 10px; cursor: pointer"
        @click="activeMenu = ''"
      />
    </div>
    <div class="typhoon_list_data">
      <table class="year-table">
        <thead>
          <tr>
            <th>年份</th>
          </tr>
        </thead>
        <tbody>
          <tr
            v-for="(item, index) in yearsTable"
            :key="item.year"
            @click="selectYear(item.year, index)"
            :class="item.checked ? 'checked' : ''"
          >
            <td>{{ item.year }}</td>
          </tr>
        </tbody>
      </table>
      <table class="typhoon-table">
        <thead>
          <tr>
            <th style="width: 40px"></th>
            <th>编号</th>
            <th>中文名</th>
            <th>英文名</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in typhoonTable" :key="item.id">
            <td style="width: 40px">
              <input
                type="checkbox"
                class="typhoon_checked"
                v-model="item.checked"
                @change="selectTyphoon(item)"
              />
            </td>
            <td>{{ item.id }}</td>
            <td>{{ item.name }}</td>
            <td>{{ item.engName }}</td>
          </tr>
        </tbody>
      </table>
    </div>
    <div class="typhoonInfo-title">台风图例</div>
    <div class="box-typhoon-legend" style="height: 80px">
      <div class="box-power">
        <div class="legend-power-row">
          <div
            class="legend-power-dot"
            style="border: 3px solid rgba(2, 255, 2, 1)"
          ></div>
          <div class="legend-power-text">热带低压</div>
        </div>
        <div class="legend-power-row">
          <div
            class="legend-power-dot"
            style="border: 3px solid rgb(19, 98, 177)"
          ></div>
          <div class="legend-power-text">热带风暴</div>
        </div>
        <div class="legend-power-row">
          <div
            class="legend-power-dot"
            style="border: 3px solid rgba(255, 251, 5, 1)"
          ></div>
          <div class="legend-power-text">强热带风暴</div>
        </div>
      </div>
      <div class="box-power">
        <div class="legend-power-row">
          <div
            class="legend-power-dot"
            style="border: 3px solid rgba(255, 172, 5, 1)"
          ></div>
          <div class="legend-power-text">台风</div>
        </div>
        <div class="legend-power-row">
          <div
            class="legend-power-dot"
            style="border: 3px solid rgba(241, 113, 249, 1)"
          ></div>
          <div class="legend-power-text">强台风</div>
        </div>
        <div class="legend-power-row">
          <div
            class="legend-power-dot"
            style="border: 3px solid rgba(254, 2, 2, 1)"
          ></div>
          <div class="legend-power-text">超强台风</div>
        </div>
      </div>
    </div>
    <div id="tl_bot">
      <van-checkbox-group v-model="checked" shape="square" id="tl_bot_group">
        <van-checkbox name="a">
          <span :style="{ borderBottomColor: '#FF4050' }" class="label_span"
            >中国</span
          >
        </van-checkbox>
        <van-checkbox name="b">
          <span :style="{ borderBottomColor: '#FF83FD' }" class="label_span"
            >中国香港</span
          >
        </van-checkbox>
        <van-checkbox name="c">
          <span :style="{ borderBottomColor: '#FEB362' }" class="label_span"
            >中国台湾</span
          >
        </van-checkbox>
        <van-checkbox name="d">
          <span :style="{ borderBottomColor: '#67FF6E' }" class="label_span"
            >日本</span
          >
        </van-checkbox>
        <van-checkbox name="e">
          <span :style="{ borderBottomColor: '#83ACA8' }" class="label_span"
            >韩国</span
          >
        </van-checkbox>
        <van-checkbox name="f">
          <span :style="{ borderBottomColor: '#65E2FE' }" class="label_span"
            >美国</span
          >
        </van-checkbox>
      </van-checkbox-group>
    </div>
  </div>
  <!-- 台风popup -->
  <div id="typhoonText" class="promptText"></div>
  <!-- 当前台风信息 -->
  <div
    id="currentPop"
    v-if="chun.tfInfo.name != ''"
    :style="{ left: popPositon.left + 'px', top: popPositon.top + 'px' }"
  >
    <div id="currentPop_header">
      <div class="pop_title" style="margin-right: 10px; color: white">
        {{ chun.tfInfo.name }}
      </div>
      <div class="pop_title" style="color: white">
        {{ getChDate(chun.tfInfo.time) }}
      </div>
      <img
        :src="iconClose"
        alt=""
        style="
          margin-left: auto;
          margin-right: 5px;
          height: 15px;
          cursor: pointer;
        "
        @click="chun.tfInfo.name = ''"
      />
    </div>
    <div class="my-swipe" :loop="false">
      <!-- 两个圆圈切换按钮 -->
      <div class="qqq">
        <div
          v-for="(item, index) in chun.tfInfo.moveSpeed ||
          !chun.tfInfo.radius.includes('-')
            ? 2
            : 0"
          :key="index"
          :style="{ backgroundColor: index == activePage ? '#4a90e2' : '#ccc' }"
          @click="activePage = index"
        ></div>
      </div>

      <div v-if="activePage == 0">
        <el-row>
          <el-col :span="7">
            <div class="pop_title">中心位置:</div>
          </el-col>
          <el-col :span="17">
            <div class="pop_value">
              {{ chun.tfInfo.position }}
            </div>
          </el-col>
        </el-row>

        <el-row v-show="chun.tfInfo.speed && chun.tfInfo.power">
          <el-col :span="7">
            <div class="pop_title">风速风力:</div>
          </el-col>
          <el-col :span="17">
            <div class="pop_value">
              {{ chun.tfInfo.speed }} {{ chun.tfInfo.power }}
            </div>
          </el-col>
        </el-row>

        <el-row v-show="chun.tfInfo.pressure">
          <el-col :span="7">
            <div class="pop_title">中心气压:</div>
          </el-col>
          <el-col :span="17">
            <div class="pop_value">
              {{ chun.tfInfo.pressure }}
            </div>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="10">
            <div class="pop_title">距离关注区域:</div>
          </el-col>
          <el-col :span="14">
            <div
              class="pop_value"
              style="font-weight: bold; color: #f00; font-family: 'aliph500'"
            >
              {{ chun.tfInfo.distance }}
            </div>
          </el-col>
        </el-row>
      </div>
      <template
        v-if="
          (chun.tfInfo.moveSpeed || !chun.tfInfo.radius.includes('-')) &&
          activePage == 1
        "
      >
        <div>
          <el-row v-show="chun.tfInfo.moveSpeed">
            <el-col :span="10">
              <div class="pop_title">移速移向:</div>
            </el-col>
            <el-col :span="14">
              <div class="pop_value">
                {{ chun.tfInfo.moveSpeed }} {{ chun.tfInfo.moveDir }}
              </div>
            </el-col>
          </el-row>

          <el-row v-show="!chun.tfInfo.radius.includes('-')">
            <el-col :span="10">
              <div class="pop_title">风圈半径(7级):</div>
            </el-col>
            <el-col :span="14">
              <div class="pop_value">
                {{ chun.tfInfo.radius.split("/")[0] }}km
              </div>
            </el-col>
          </el-row>
          <el-row v-show="!chun.tfInfo.radius.includes('-')">
            <el-col :span="10">
              <div class="pop_title">风圈半径(10级):</div>
            </el-col>
            <el-col :span="14">
              <div class="pop_value">
                {{ chun.tfInfo.radius.split("/")[1] }}km
              </div>
            </el-col>
          </el-row>
          <el-row v-show="!chun.tfInfo.radius.includes('-')">
            <el-col :span="10">
              <div class="pop_title">风圈半径(12级):</div>
            </el-col>
            <el-col :span="14">
              <div class="pop_value">
                {{ chun.tfInfo.radius.split("/")[2] }}km
              </div>
            </el-col>
          </el-row>
        </div>
      </template>
    </div>
  </div>

  <div id="wtf" v-show="!isTfNow && typhoonLength == 0">
    <!-- 当前无台风 -->
    <img src="../../../assets/img/wtf.png" alt="" style="height: 100px" />
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, reactive, watch } from "vue";
import { getTyphoonYears, getTyphoonByYear } from "./api/typhoon";
import { typhoon } from "./js/Class_Typhoon";
import { getTyphoonRouteByID } from "../../../network/net.js";
import chun from "../../../stores/chun.js";
import { mapCenter } from "../../../stores/chun.js";
import iconClose from "../../../assets/img/关闭.png";
import { activeMenu } from "../../../stores/chun.js";

const props = defineProps({
  map: {
    type: Object,
    required: true,
  },
});

const checked = ref(["a", "b", "c", "d", "e", "f"]);
const activePage = ref(0);

watch([chun.tfInfo, mapCenter], () => {
  if (!chun.tfInfo.position) return;
  let lon = chun.tfInfo.position.split("东经")[1].split("°")[0];
  let lat = chun.tfInfo.position.split("北纬")[1].split("°")[0];
  // 根据经纬度计算弹窗位置

  let latLng = L.latLng([lat, lon]);
  let point = props.map.latLngToContainerPoint(latLng);
  popPositon.left = point.x - 10;
  popPositon.top = point.y - 180;
});

const popPositon = reactive({ left: 0, top: 0 });

const isOpen = ref(true);
const years = ref([]);
const typhoons = ref({});
const yearsTable = ref([]);
const typhoonTable = ref([]);

// 当前台风信息
const currentTyphoon = ref({
  name: "",
  engName: "",
  position: "",
  distance: "",
});
let isTfNow = ref(false);
let tfBhNow = [];

const getChDate = (date) => {
  if (!date) return "";
  let dateArr = date.split(" ")[0].split("-");
  let hour = date.split(" ")[1].split(":")[0];
  return `${dateArr[0]}年${dateArr[1]}月${dateArr[2]}日 ${hour}时`;
};

const moveMethod = (e) => {
  // 获取地图中心点
  let center = props.map.getCenter();
  mapCenter.value = center;
};

function formatDate(date) {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  return `${year}-${month}-${day}`;
}

onMounted(() => {
  getTyphoonByYear({ year: new Date().getFullYear() }).then((res) => {
    
    let result = res.data.data[res.data.data.length - 1];
    
    const today = new Date();
    res.data.data.forEach((i) => {
      if (i.endTime.split(" ")[0] == formatDate(today)) {
        tfBhNow.push(i.tfbh);
        isTfNow.value = true;
        isOpen.value = true;

        currentTyphoon.value.name = result.name;
        currentTyphoon.value.engName = result.ename;

        
        getTyphoonRouteByID(result.tfbh).then((res1) => {
          
          let info = res1.data.data;
          
          let currentPoint = info[info.length - 1];
          currentTyphoon.value.position = `东经${currentPoint.JD}° 北纬${currentPoint.WD}°`;
          let basePosition = [30.438361, 120.954109];
          let distance = Math.sqrt(
            Math.pow(currentPoint.JD - basePosition[1], 2) +
              Math.pow(currentPoint.WD - basePosition[0], 2)
          );
          currentTyphoon.value.distance = `${(distance * 100).toFixed(2)}km`;
        });
      }
    });
  });

  init();

  props.map.on("move", moveMethod);
});

onUnmounted(() => {
  typhoon.removeAllPath();
  typhoon.removeWarningLine();

  // 移除地图的移动事件
  props.map.off("moveend", moveMethod);
});

const init = () => {
  // 判断地图是否加载完成
  if (!props.map) {
    router.push({
      path: "/home",
    });
    return;
  }
  //初始化台风
  typhoon.init({
    map: props.map,
  });
  typhoon.drawTodayTyphoon();
  typhoon.addWarningLine();

  //加载年份数据
  getTyphoonYears().then((res) => {
    // res.data = res.data;
    // res.data.data.map((item) => {
    //   item.year = item.years;
    // });

    
    let arr = [];
    for (let i = 0; i < res.data.data.length; i++) {
      const el = res.data.data[i];
      if (el.year > 2016) {
        arr.push(el);
      }
    }
    years.value = arr;
    

    yearsTable.value = arr.map((item) => {
      return {
        year: `${item.year}年`,
        checked: false,
      };
    });
    // 预加载近4年台风详情
    let ys = years.value.length >= 10 ? 4 : years.value.length;
    for (let i = 0; i < ys; i++) {
      typhoons.value[years.value[i].year] = [];
      getTyphoonByYear(years.value[i]).then((res) => {
        
        if (res.data.code==200) {
          res.data = res.data;
          

          // let is_current = 0;
          const today = new Date();
          // if (item.endTime.split(" ")[0] == formatDate(today)) {
          //   is_current = 1;
          // }
          res.data.data.map((item) => {
            item.ename = item.ename;
            item.name = item.name;
            item.tfbh = item.tfbh;
            item.ident = item.tfbh;
            item.is_current =
              item.endTime.split(" ")[0] == formatDate(today) ? 1 : 0;
            item.land = item.TFLAND;
            item.begin_time = item.beginTime;
            item.end_time = item.endTime;
          });

          // 根据tfbh升序排序
          res.data.data.sort((a, b) => {
            // return b.tfbh - a.tfbh;
            return a.tfbh - b.tfbh;
          });
        }

        let d = res.data.data;
        let currentYear = new Date().getFullYear();

        if (d) {
          for (let j = d.length - 1; j >= 0; j--) {
            // for (let j = 0; j < d.length; j++) {
            if (d[j].tfbh.length >= 8) continue;
            typhoons.value[years.value[i].year].push({
              id: d[j].tfbh,
              name: d[j].name,
              engName: d[j].ename,
              checked: tfBhNow.includes(d[j].tfbh),
            });
          }
        }
      });
    }
    //默认选中
    
    selectYear(yearsTable.value[0].year, 0);
  });
};

//年份表格单选事件
let lastIndex = 0;
const selectYear = (e, i) => {
  yearsTable.value[lastIndex].checked = false;
  yearsTable.value[i].checked = true;
  lastIndex = i;

  const yearIndex = e.indexOf("年"); // 查找年份字符的位置
  const year = e.substring(0, yearIndex);
  //该年份是否已经缓存
  if (typhoons.value[year]) {
    typhoonTable.value = typhoons.value[year];
    
  } else {
    typhoons.value[year] = [];
    getTyphoonByYear({ year }).then((res) => {
      //2023无数据
      let d = res.data.data;
      if (d) {
        for (let j = d.length - 1; j >= 0; j--) {
          // for (let j = 0; j < d.length; j++) {
          if (d[j].tfbh.length >= 8) continue;
          typhoons.value[years.value[i].year].push({
            id: d[j].tfbh,
            name: d[j].name,
            engName: d[j].ename,
            checked: false,
          });
        }
      }
      typhoonTable.value = typhoons.value[year];
    });
  }
};
let typhoonLength = ref(0);
//台风表格多选事件
// const selectTyphoon = e => {
//   let { id: typhoonId, name, engName: ename, checked: ischecked } = e
//   if (ischecked) {
//     typhoonLength.value = typhoon.typhoonIdArray.length + 1
//     typhoon.drawTyphoon({
//       tfbh: typhoonId,
//       name: name,
//       ename: ename
//     })
//   } else {
//     typhoonLength.value = typhoon.typhoonIdArray.length - 1
//     typhoon.removeOnePath(typhoonId)
//     typhoonId = typhoon.typhoonIdArray[typhoon.typhoonIdArray.length - 1]
//   }
// }

const selectTyphoon = (e) => {
  let { id: typhoonId, name, engName: ename, checked: ischecked } = e;
  // chun.tfInfo.name=name
  // chun.tfInfo.engName=ename
  if (ischecked) {
    typhoonLength.value = typhoon.typhoonIdArray.length + 1;
    typhoon.drawTyphoon({
      tfbh: typhoonId,
      name: name,
      ename: ename,
    });
  } else {
    typhoonLength.value = typhoon.typhoonIdArray.length - 1;
    typhoon.removeOnePath(typhoonId);
    typhoonId = typhoon.typhoonIdArray[typhoon.typhoonIdArray.length - 1];
  }
};
</script>

<style>
@import "./style/typhoon.css";
</style>
<style lang="less" scoped>
#tl_bot {
  flex: 1;
  display: flex;
  width: 100%;
  flex-wrap: wrap;
  height: 80px;
  padding: 10px;
  border-top: 1px solid #e8e8e8;
}

#tl_bot_group {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
}

:deep(.van-checkbox__label) {
  font-size: 14px !important;
  font-family: "aliph400";
  display: flex;
  align-items: center;
  width: 30px;
  white-space: nowrap;
}

:deep(.van-badge__wrapper) {
  height: 1rem;
  width: 1rem;
  line-height: 1rem;
  margin-top: 2px;
}

:deep(.van-badge__wrapper::before) {
  line-height: 1rem;
}

:deep(.van-checkbox) {
  width: 33%;
  height: 50%;
}

.label_span {
  border-bottom: 2px dashed rgb(106, 98, 98);
}

.qqq {
  position: absolute;
  bottom: 10px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  div {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    margin: 0 5px;
    cursor: pointer;
    // 灰色
    background-color: #ccc;
    transition: background-color 0.2s;
  }
}
</style>
